import express from "express";
import { task } from "../../db/tasks/my_tasks.js";

const router = express.Router();

router.get("/get_task", async (req, res) => {
  const { name, card, type, start_time, end_time, user, executor, status } =
    req.query;
  const query = {};
  if (name) {
    query.$or = [{ name: { $regex: name, $options: "i" } }];
  }
  if (card) {
    query.$or = [{ card: { $regex: card, $options: "i" } }];
  }
  if (type) {
    query.$or = [{ type: { $regex: type, $options: "i" } }];
  }
  if (start_time) {
    query.$or = [{ start_time: { $regex: start_time } }];
  }
  if (end_time) {
    query.$or = [{ end_time: { $regex: end_time } }];
  }
  if (user) {
    query.$or = [{ user: { $regex: user, $options: "i" } }];
  }
  if (executor) {
    query.$or = [{ executor: { $regex: executor, $options: "i" } }];
  }
  if (status) {
    query.$or = [{ status: { $regex: status } }];
  }
  console.log(req.query);

  const data = await task.find(query);
  res.send({ data });
});

router.post("/add_task", async (req, res) => {
  await task.create(req.body);
  console.log(req.body);
  res.send({
    code: 200,
  });
});
router.put("/updateStatus", async (req, res) => {
  const { id, status } = req.body;

  await task.updateOne({ _id: id }, { status: status });
  res.send({
    code: 200,
  });
});
router.put("/updateProgress", async (req, res) => {
  const { id, progress } = req.body;
  console.log(req.body);
  await task.updateOne({ _id: id }, { progress: progress });
  res.send({
    code: 200,
  });
});
router.delete("/deleteTask", async (req, res) => {
  const { id } = req.body;
  console.log(id);
  await task.deleteOne({ _id: id });
  res.send({
    code: 200,
  });
});
export default router;
